/**
 * Created by Skipper on 2017/4/14.
 */
import React, {PropTypes} from 'react';
import {Icon, Spin, Collapse, Input, Switch, Menu, Modal, Row, Col, Button, message, Table} from 'antd';
import {connect} from 'react-redux'
import {GoogleMap, withGoogleMap, Marker, Polyline, InfoWindow} from "react-google-maps";
import withScriptjs from "react-google-maps/lib/async/withScriptjs";
import WebsocketComp from './websocket';
import {
  system_status_flag,
  mission_ack_flag,
  command_ack_flag,
  command_ack_flag_name,
  infosConst,
  control_icons
} from './commonData';
import {formatDateToHourAndSeconds} from './common';
import classNames from 'classnames'
import {gcj02towgs84, wgs84togcj02} from './coordtransform';

const REBACKIMG = require('../images/cloudlogo.png');
const CLOSEREBACKIMG = require('../images/ftminus.png');
const CONTROLICONS = {
  FOLLOWFLIGHT: require('../images/followflight.png'),
  REMOTE: require('../images/remote.png'),
  TUCENG: require('../images/tuceng.png'),
  GPS: require('../images/gps.png'),

  FOLLOWFLIGHTACTIVE: require('../images/followflight-atv.png'),
  TUCENGACTIVE: require('../images/tuceng-atv.png'),
}
var imageReturn = {};
var imageAllData = '';
var fIconSpanCls = 'f-icon-span';
const Panel = Collapse.Panel;
const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
const FLIGHTMARKER = require('../images/flight.png');
const MARKERBLUE = require('../images/mark-bs.png');
const AsyncGettingStartedExampleGoogleMap = withScriptjs(
  withGoogleMap(
    props => (
      <GoogleMap
        ref={props.onMapLoad}
        defaultZoom={props.mapdefaultProps.zoom}
        defaultCenter={props.mapdefaultProps.center}
        center={props.center}
        mapTypeId={props.mapTypeId}
        onClick={props.onMapClick}
      >
        {
          props.markers.map(marker => {
            const onClick = () => props.onMarkerClick(marker);

            const onMouseOver = () => props.onMarkerMouseOver(marker);
            const onMouseOut = () => props.onMarkerMouseOut(marker);
            const onCloseClick = () => props.onCloseClick(marker);
            const setZIndex = () => marker.isHover ? props.onMarkerSetZIndex(marker, 2) : props.onMarkerSetZIndex(marker, 0);
            return (
              <Marker
                {...marker}
                draggable={true}
                onRightClick={() => props.onMarkerRightClick(marker)}
                onDrag={(e)=>props.onMarkerDrag(e, marker)}

                onClick={onClick}
                onMouseOver={onMouseOver}
                onMouseOut={onMouseOut}
                setZIndex={setZIndex}
              >
                {
                  (marker.showInfo || marker.isHover) && (
                    <InfoWindow onCloseClick={onCloseClick}>
                      <div>
                        <strong>{marker.content}</strong>
                        <p><span>{`Lon：${marker.position.lng}`}</span></p>
                        <p><span>{`Lat：${marker.position.lat}`}</span></p>
                        <p><span>{`速度：${marker.v}`}</span></p>
                        <p><span>{`高度：${marker.alt}`}</span></p>
                        <p><span>{`编号：${marker.title}`}</span></p>
                      </div>
                    </InfoWindow>
                  )
                }
              </Marker>
            )
          })
        }
        <Marker
          {...props.flightMarker}
        />
        <Polyline
          path={props.polylineArr}
          strokeColor={'#e63f00'}
          strokeOpacity={1}
          strokeWeight={3}
          strokeStyle={"solid"}
          key={Date.now()}
        />
      </GoogleMap>
    )
  )
)
class ReactGoogleMapsComp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isMapLoaded: false,
      mapdefaultProps: {
        center: {
          lat: 29.123456, lng: 119.123456
        },
        zoom: 13
      },
      center: {
        lat: 29.123456, lng: 119.123456
      },
      mapTypeId: 'roadmap',

      flightstatedata: [],
      markers: [],
      polylineArr: [],
      pointLists: [],

      pointsAllChecked: true,
      pointsActive: ['0'],

      leftIconStatus: true,
      rightIconStatus: true,
      bottomIconStatus: true,
      infos: infosConst,
      isFlightID: false,
      flightID: '',
      flightMarker: {},
      token: '',
      airWayRebackImage: false,
      isairWayRebackImage: false,
      // iconStatus: [
      //   {'name': 'mmc', 'value': 0},
      //   {'name': 'fc', 'value': 0},
      //   {'name': 'local', 'value': 0},
      //   {'name': '3g', 'value': 0},
      //   {'name': 'camera', 'value': 0},
      //   {'name': 'ultrasonic', 'value': 0},
      //   {'name': 'camerab1', 'value': 0},
      //   {'name': 'b2', 'value': 0},
      // ]
      iconStatus: {
        mmc: 0,
        fc: 0,
        local: 0,
        '3g': 0,
        camera: 0,
        ultrasonic: 0,
        camerab1: 0,
        b2: 0
      },

      localSignalStatus: true,
      wideSignalStatus: true,
      WebSocket: null,
      isWebsocket: false,

      missionPauseStatus: false,

      isfollowAllTheTime: false,

      remoteControlVisible: false,
      remoteImg: REBACKIMG,
      imgUpdata: 0,
      horizonIntervalNum: 0,
      verticalIntervalNum: 0,
      airWayImageStyle: {},
      spanXText: '',
      spanYText: '',
      XSpanStyle: {
        position: 'absolute', color: 'red',
      },
      YSpanStyle: {
        position: 'absolute', color: 'red',
      },

      uavSlowDownVisible: false,
      uavPidVisible: false,
      uavXPPidVisible: false,
      uavOffSetVisible: false,
      uavLocalGpsOffsetVisible: false,
      uavEmLandInfoSetVisible: false,
      flightSlowDownModal: false,

      saveAirwayVisible: false,
      searchAirwayVisible: false,

      spanXTextInput: '',
      spanYTextInput: '',
      spanZTextInput: '',

      flightSlowDownValue: '',
      pidValue1: '',
      pidValue2: '',
      pidValue3: '',
      pidValue4: '',
      pidValue5: '',
      pidValue6: '',
      pidValue7: '',
      offSetLon: '',
      offSetLat: '',
      uavLocalGpsOffsetValue: '',

      saveAirwayName: '',
      searchAirwayName: '',
      airWaydatas: [],
      rowSelectData: [],

      selectedRowKeys: [],
    }
  }

  componentWillMount() {
    // console.log('当前route id 是 ', (this.props.location.search).split('?id=')[1], ' this.props.location ', this.props.location);
    let arg = (this.props.location.search).split('?id=');
    let newArg = arg[1].split('&t=');
    console.log('当前route id 是 ', (this.props.location.search).split('?id=')[1], ' this.props.location ', this.props.location, ' arg is ', arg, ' newArg is ', newArg);
    let id, token;
    if (newArg) {
      id = newArg[0];
      token = newArg[1];
    } else {
      id = arg[1];
    }
    this.setState({
      flightID: id,
      isFlightID: true,
      token: token,
    })
  }

  componentDidMount() {
    let mapArea = document.getElementById('mapContainer');
    let totalWidth = mapArea.offsetWidth - document.getElementById('SRight').offsetWidth;
    let totalHeight = mapArea.offsetHeight - 86 - 88;
    let imageWidth = (totalWidth - 32) * 0.75 - 16;
    let imageHeight = totalHeight - 50 - 32;
    // console.log('totalWidth is :', totalWidth, '  totalHeight is :', totalHeight, '  imageWidth is :', imageWidth, '  imageHeight is :', imageHeight)
    this.setState({
      airWayImageStyle: {
        height: totalHeight,
        width: totalWidth,
        marginTop: 54,
        marginLeft: 180,
        paddingBottom: 0,
      },
      centerRecStyle: {
        width: imageWidth * 0.125,
        height: imageHeight * 2 / 9,
        marginTop: -(imageHeight) / 9,
        marginLeft: -imageWidth * 0.125 / 2
      },
      centerCircleStyle: {
        width: imageWidth * 0.375,
        height: imageHeight * 2 / 3,
        marginTop: -(imageHeight) / 3,
        marginLeft: -imageWidth * 0.375 / 2
      },
      imageWidth: imageWidth,
      imageHeight: imageHeight,
    });
  }

  handleMapLoad = (map)=> {
    this._mapComponent = map;
    if (map) {
      console.log('当前缩放级别是  ', map.getZoom());
      this.setState({
        isMapLoaded: true,
        flightMarker: {
          ...this.state.flightMarker,
          position: {lat: 29.123456, lng: 119.123456},
          defaultAnimation: 2,
          draggable: false,
          key: Date.now(),
          icon: {
            url: FLIGHTMARKER,
            scaledSize: new google.maps.Size(50, 50),
            size: new google.maps.Size(50, 50),
            origin: new google.maps.Point(0, 0),//The position of the image within a sprite, if any. By default, the origin is located at the top left corner of the image (0, 0)
            anchor: new google.maps.Point(25, 25),//The position at which to anchor an image in correspondence to the location of the marker on the map. By default, the anchor is located along the center point of the bottom of the image(25,50).
            labelOrigin: new google.maps.Point(25, 22)
          },
          label: {
            text: this.state.flightID ? this.state.flightID.toString() : 'jetgo-map',
            color: '#fff',
            fontSize: '12',
          },
          title: this.state.flightID ? this.state.flightID.toString() : 'jetgo-map',
          // data: this.state.infos
        }
      });
    }
  }

  /*****
   * This is called when you click on the map.
   * Go and try click now.
   */
  handleMapClick = (event)=> {
    // console.log(event.latLng)
    let nextPosition = {
      lat: event.latLng.lat(),
      lng: event.latLng.lng(),
    };
    let curInputPosition = gcj02towgs84(nextPosition.lng, nextPosition.lat);
    const nextMarkers = [
      ...this.state.markers,
      {
        position: nextPosition,
        defaultAnimation: 2,
        draggable: true,
        key: `${Date.now()}${Date.now()}`, // Add a key property for: http://fb.me/react-warning-keys
        icon: {
          url: MARKERBLUE,
          scaledSize: new google.maps.Size(18, 32),
          size: new google.maps.Size(18, 32),
          origin: new google.maps.Point(0, 0),//The position of the image within a sprite, if any. By default, the origin is located at the top left corner of the image (0, 0)
          anchor: new google.maps.Point(9, 29),//The position at which to anchor an image in correspondence to the location of the marker on the map. By default, the anchor is located along the center point of the bottom of the image(25,50).
          labelOrigin: new google.maps.Point(9, 11)
        },
        label: {
          // text: (this.state.markers.length + 1).toString(),
          text: (this.state.markers.length).toString(),
          color: '#fff',
          fontSize: '12',
        },
        title: (this.state.markers.length).toString(),
        showInfo: false,
        isHover: false,
        zIndex: 0,
        content: `欢迎来到${(this.state.markers.length).toString()}号空间站`,
        v: '2.0', alt: '25',
      }
    ];
    const nextPolyline = [
      ...this.state.polylineArr,
      nextPosition,
    ];
    let points = nextMarkers.map(marker=> {
      return {
        'title': '航点',
        'id': marker.title,
        'label1': '经度',
        'label2': '纬度',
        'label3': '速度',
        'label4': '高度',
        'lon': curInputPosition[0],
        'lat': curInputPosition[1],
        'v': '2.00',
        'alt': '25.00',
      }
    })

    this.setState({
      markers: nextMarkers,
      polylineArr: nextPolyline,
      pointLists: points
    });
  }

  handleMarkerRightClick = (targetMarker) => {
    /*
     * All you modify is data, and the view is driven by data.
     * This is so called data-driven-development. (And yes, it's now in
     * web front end and even with google maps API.)
     */
    const nextMarkers = this.state.markers.filter(marker => marker !== targetMarker);
    this.setState({
      markers: nextMarkers,
    });
  }

  /*****
   * 这是一个令人痛不欲生的函数——真正的好事多磨！想想就酸爽。。。
   * 通过给marker绑定drag事件，然后动态改变polyline和右侧输入框的值，一开始某人只给某个特定marker绑定drag事件（onDrag={() => props.onMarkerDrag(marker)}），
   * 传递的参数是marker本身，所以怎么拖动，marker都是恒定的，所以polyline和input值不会变动，虽然marker的位置改变了。
   * 尝试了各种强制update，各种变相写法，均无效，因为marker一直未变。真是bi了整个React！！！然后，各种折腾，，，原来是要把
   * 地图本身事件（当前经纬度） 和当前marker（需要改变的marker）同时传递过去。onDrag={(e)=>props.onMarkerDrag(e, marker)}，，，没错，
   * 就是这货。折腾老子这么久。。。真是那句话——自己犯二，怨不得别人。
   *
   * @param event
   * @param targetMarker
   */
  handleMarkerDrag = (event, targetMarker) => {
    // console.log(event, targetMarker,event.latLng.lat(), event.latLng.lng())
    let markertitle = targetMarker.title.toString();
    let nextPosition = {
      lat: event.latLng.lat(),
      lng: event.latLng.lng(),
    };
    let curInputPosition = gcj02towgs84(nextPosition.lng, nextPosition.lat);
    this.setState({
      polylineArr: this.state.polylineArr.map((polyline, index)=> {
        // console.log('index is ', index, '  title is ', markertitle, index == markertitle)
        if (markertitle == index.toString()) {
          // console('老实交代，你有没有好好干活')
          polyline = {lat: event.latLng.lat(), lng: event.latLng.lng()};
          return polyline
        }
        return polyline;
      }),
      markers: this.state.markers.map(marker => {
        if (marker.title == markertitle) {
          return {
            ...marker,
            position: nextPosition,
          }
        }
        return marker;
      }),
      pointLists: this.state.markers.map(marker => {
        return {
          'title': '航点',
          'id': marker.title,
          'label1': '经度',
          'label2': '纬度',
          'label3': '速度',
          'label4': '高度',
          'lon': curInputPosition[0],
          'lat': curInputPosition[1],
          'v': '2.00',
          'alt': '25.00',
        };
      }),
    });
  }

  onMarkerMouseOver = (targetMarker)=> {
    this.setState({
      markers: this.state.markers.map((marker, index)=> {
        if (marker === targetMarker) {
          return {
            ...marker,
            isHover: true,
            icon: {
              url: MARKERBLUE,
              scaledSize: new google.maps.Size(27, 48),
              size: new google.maps.Size(27, 48),
              labelOrigin: new google.maps.Point(14, 14)
            },
            label: {
              text: index.toString(),
              color: '#fff',
              fontSize: '16',
            },
          }
        }
        return marker;
      }),
    });
  }

  onMarkerMouseOut = (targetMarker)=> {
    this.setState({
      markers: this.state.markers.map((marker, index)=> {
        if (marker === targetMarker) {
          return {
            ...marker,
            isHover: false,
            icon: {
              url: MARKERBLUE,
              scaledSize: new google.maps.Size(18, 32),
              size: new google.maps.Size(18, 32),
              origin: new google.maps.Point(0, 0),//The position of the image within a sprite, if any. By default, the origin is located at the top left corner of the image (0, 0)
              anchor: new google.maps.Point(9, 29),//The position at which to anchor an image in correspondence to the location of the marker on the map. By default, the anchor is located along the center point of the bottom of the image(25,50).
              labelOrigin: new google.maps.Point(9, 11)
            },
            label: {
              text: index.toString(),
              color: '#fff',
              fontSize: '12',
            },
          }
        }
        return marker;
      }),
    });
  }

  handleMarkerClick = (targetMarker)=> {
    this.setState({
      markers: this.state.markers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
    });
  }

  handleCloseClick = (targetMarker)=> {
    this.setState({
      markers: this.state.markers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),
    });
  }

  /****
   * websocket处理数据
   * @param data
   */
  websocketOnPen(arg) {
    console.log('ws is ', arg);
    let _this = this;
    /*****WS存在且readyState==1，即已连接*****/
    if (arg.target.readyState && arg.target.readyState == 1) {
      let WS = arg.target;
      let token = _this.state.token;
      this.setState({
        isWebsocket: true,
        WebSocket: WS,
      });
      if (token) {
        let WSData = [
          249,
          _this.state.flightID,
          token.length
        ];
        for (var i = 0; i < token.length; i++) {
          WSData[i + 3] = token[i].charCodeAt();
        }
        console.log('发送的数据是 ', JSON.stringify(WSData));
        // WS.send(JSON.stringify(WSData));
      } else {
        let WSData = [
          249,
          _this.state.flightID
        ];
        console.log('发送的数据是 ', JSON.stringify(WSData));
        // WS.send(JSON.stringify(WSData));
      }
    }
  }

  handleData(data) {
    let _this = this;
    if (data == 'undefined') {
      return;
    }
    let gettype = Object.prototype.toString;
    let resdt, msgid;
    let begin = 0;
    var finalData = data;
    if (gettype.call(data) == '[object ArrayBuffer]') {
      resdt = new DataView(data);
      msgid = resdt.getUint8(begin);
      /*****console.info('新协议数据是 ', resdt, ' 数据类型是  ', typeof resdt, '  ', gettype.call(data),'  数据内存长度是（字节数） ',resdt.byteLength,' msgid is ', msgid, resdt.getUint8(++begin));*****/
    } else {
      resdt = JSON.parse(data);
      msgid = resdt[begin];
    }

    // console.log('msgid is ', msgid);
    /*======飞机msg数据======*/
    if (msgid == 1) {
      /*****心跳包heartbeat*****/
      begin += 1;
      /*****第一次进来判断当前页面飞机id是否存在,,,飞机离线或者websocket断开是否需要重置呢？*****/
      if (!_this.state.isFlightID) {
        _this.setState({
          isFlightID: true,
          flightID: resdt[begin]
        })
      }
      if (resdt[begin] == _this.state.flightID) {
        let heartbeat = {};
        heartbeat['id_uav_xyi'] = resdt[begin];
        begin += 1;
        heartbeat['id_iso_xyi'] = resdt[begin];
        begin += 1;
        heartbeat['base_mode'] = resdt[begin];
        begin += 1;
        heartbeat['system_status'] = resdt[begin];
        begin += 1;
        heartbeat['xylink_version'] = resdt[begin];
        begin += 1;
        let curPosition;
        if (_this.state.infos.isGPS) {
          curPosition = {
            lat: wgs84togcj02(_this.state.infos.gps_raw.lon_gps, _this.state.infos.gps_raw.lat_gps)[1],
            lng: wgs84togcj02(_this.state.infos.gps_raw.lon_gps, _this.state.infos.gps_raw.lat_gps)[0],
          };
        } else {
          curPosition = _this.state.flightMarker.position
        }

        _this.setState({
          infos: {
            ..._this.state.infos,
            heartbeat: heartbeat,
          },
          flightMarker: {
            ..._this.state.flightMarker,
            position: curPosition,
            label: {
              text: this.state.flightID.toString(),
              color: '#fff',
              fontSize: '12',
            },
            title: this.state.flightID.toString(),
          }
        });
        if (_this.heartbeatTimeout) {
          clearTimeout(_this.heartbeatTimeout);
        }
        /*****一定时间未收到心跳包，设置状态*****/
        _this.heartbeatTimeout = setTimeout(function () {
          _this.setState({
            wideSignalStatus: false,
            localSignalStatus: false,
            infos: {
              ..._this.state.infos,
              heartbeat: {
                ..._this.state.infos.heartbeat,
                base_mode: '0'
              }
            }
          })
        }, 8000);
        _this.changeIconStatus();
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 2) {
      /*****电池battery_status*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        begin += 1;
        let battery_status = {};
        battery_status['time_std_s'] = 0;
        battery_status['time_std_s'] = resdt[begin];
        begin += 1;
        battery_status['voltages'] = [];
        for (var i = 0; i < 10; i++) {
          battery_status['voltages'][i] = (resdt[begin] / 1000).toFixed(2);
          begin += 1;
        }
        battery_status['voltages'] = battery_status['voltages'][0];
        battery_status['current_battery'] = resdt[begin];
        begin += 1;
        battery_status['battery_remaining'] = resdt[begin];
        begin += 1;
        battery_status['battery_life_factor'] = resdt[begin];
        begin += 1;
        battery_status['uav_load_factor'] = resdt[begin];
        begin += 1;
        battery_status['time_can_fly'] = resdt[begin];
        begin += 1;
        battery_status['time_needed'] = resdt[begin];
        begin += 1;
        _this.setState({
          infos: {
            ..._this.state.infos,
            battery_status: battery_status,
          }
        });
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 3) {
      /*****相对坐标local_position_ned*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        begin += 1;
        let local_position_ned = {};
        local_position_ned['time_std_s'] = 0;
        local_position_ned['time_std_s'] = resdt[begin];
        local_position_ned['loseWSTime'] = local_position_ned['time_std_s'];
        begin += 1;
        local_position_ned['time_std_s'] = formatDateToHourAndSeconds(local_position_ned['time_std_s']);
        local_position_ned['x'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['y'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['z'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['vx'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['vy'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['vz'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['ultra_alt'] = (resdt[begin] * 1).toFixed(2);
        begin += 1;
        local_position_ned['vz02'] = local_position_ned['vz'] * (-1);
        local_position_ned['dis_m'] = (resdt[begin] * 1).toFixed(1);
        begin += 1;
        _this.setState({
          infos: {
            ..._this.state.infos,
            local_position_ned: local_position_ned,
          }
        });
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 4) {
      /*****绝对坐标global_position_int*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        begin += 1;
        let global_position_int = {};
        global_position_int = {};
        global_position_int['time_std_s'] = 0;
        global_position_int['time_std_s'] = resdt[begin];
        let time_step = new Date().getTime() / 1000 - resdt[begin];
        let last_date = resdt[begin];
        begin += 1;
        global_position_int['relative_alt'] = (resdt[begin]).toFixed(1);
        begin += 1;
        global_position_int['pitch_deg'] = resdt[begin];
        begin += 1;
        global_position_int['roll_deg'] = resdt[begin];
        begin += 1;
        global_position_int['hdg'] = resdt[begin];
        begin += 1;
        _this.setState({
          infos: {
            ..._this.state.infos,
            global_position_int: global_position_int,
            time_step: time_step,
            last_date: last_date,
            isInfos: true,
          }
        });
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 5) {
      /*****GPS数据gps_raw*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        begin += 1;
        let gps_raw = {};
        gps_raw['time_std_s'] = 0;
        gps_raw['time_std_s'] = resdt[begin];
        let time_step = new Date().getTime() / 1000 - resdt[begin];
        let last_date = resdt[begin];
        begin += 1;
        gps_raw['fix_type'] = resdt[begin];
        begin += 1;
        let lat = parseFloat(resdt[begin]);
        gps_raw['lat_gps'] = lat;
        begin += 1;
        let lon = parseFloat(resdt[begin]);
        gps_raw['lon_gps'] = lon;
        begin += 1;
        let alt = parseFloat(resdt[begin]);
        gps_raw['alt_gps'] = alt;
        begin += 1;
        gps_raw['eph'] = resdt[begin];
        begin += 1;
        gps_raw['epv'] = resdt[begin];
        begin += 1;
        gps_raw['vel_gps'] = resdt[begin];
        begin += 1;
        gps_raw['vel_gps2'] = gps_raw['vel_gps'];
        gps_raw['cog'] = resdt[begin];
        begin += 1;
        gps_raw['satellites_visible'] = resdt[begin];
        begin += 1;
        _this.setState({
          infos: {
            ..._this.state.infos,
            gps_raw: gps_raw,
            time_step: time_step,
            last_date: last_date,

            isGPS: lat && lon ? true : false,
          }
        });
        if (_this.state.isfollowAllTheTime) {
          _this.setState({
            center: {
              lat: lat, lng: lon
            }
          })
        }
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 6) {
      /*****图像识别结果vision_xyz_ned*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        begin += 1;
        let vision_xyz_ned = {};
        vision_xyz_ned['time_std_s'] = 0;
        vision_xyz_ned['time_std_s'] = resdt[begin];
        let time_step = new Date().getTime() / 1000 - resdt[begin];
        let last_date = resdt[begin];
        begin += 1;
        vision_xyz_ned['vision_reg_num'] = resdt[begin];
        begin += 1;
        vision_xyz_ned['vision_x_ned'] = (resdt[begin]).toFixed(2);
        begin += 1;
        if (vision_xyz_ned['vision_x_ned'] < -25) {
          vision_xyz_ned['vision_x_ned'] = '-25.00(超程)';
        } else if (vision_xyz_ned['vision_x_ned'] > 25) {
          vision_xyz_ned['vision_x_ned'] = '25.00(超程)';
        }
        vision_xyz_ned['vision_y_ned'] = (resdt[begin]).toFixed(2);
        begin += 1;
        if (vision_xyz_ned['vision_y_ned'] < -25) {
          vision_xyz_ned['vision_y_ned'] = '-25.00(超程)';
        } else if (vision_xyz_ned['vision_y_ned'] > 25) {
          vision_xyz_ned['vision_y_ned'] = '25.00(超程)';
        }
        vision_xyz_ned['vision_z_ned'] = (resdt[begin]).toFixed(2);
        begin += 1;
        if (vision_xyz_ned['vision_z_ned'] < 0) {
          vision_xyz_ned['vision_z_ned'] = '0.00(超程)';
        } else if (vision_xyz_ned['vision_z_ned'] > 50) {
          vision_xyz_ned['vision_z_ned'] = '50.00(超程)';
        }
        _this.setState({
          infos: {
            ..._this.state.infos,
            vision_xyz_ned: vision_xyz_ned,
            time_step: time_step,
            last_date: last_date,
          }
        });
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 102) {
      /*****控制指令相应*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        begin += 1;
        let command_ack = {};
        command_ack['command'] = resdt[begin];
        begin += 1;
        command_ack['result'] = resdt[begin];
        begin += 1;
        console.log(command_ack_flag_name[command_ack['command']], command_ack['result'], command_ack_flag[command_ack['result']]);
        message.info(`${command_ack_flag_name[command_ack['command']]}: ${command_ack_flag[command_ack['result']]}`);
      }
    } else if (msgid == 106) {
      /*****航路数据应答mission_ack*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        let mission_ack = {};
        mission_ack['target_uav'] = resdt[begin];
        begin += 1;
        mission_ack['target_system'] = resdt[begin];
        begin += 1;
        mission_ack['type'] = resdt[begin];
        begin += 1;
        if (mission_ack['type'] > 0) {
          message.info(mission_ack_flag[mission_ack['type']][0]);
        }
      }
    } else if (msgid == 108) {
      /*****航路数据应答mission_ack2*****/
      begin += 1;
      /*****msgid==108这种msgid会比心跳包先返回，此时flightID未赋值*****/
      if (resdt[begin] == _this.state.flightID || !_this.state.flightID) {
        let mission_ack_2 = {};
        mission_ack_2['target_uav'] = resdt[begin];
        begin += 1;
        mission_ack_2['target_system'] = resdt[begin];
        begin += 1;
        mission_ack_2['type'] = resdt[begin];
        begin += 1;
        mission_ack_2['count'] = resdt[begin];
        begin += 1;
        mission_ack_2['frame'] = resdt[begin];
        begin += 1;
        mission_ack_2['points'] = [];
        for (var i = 0; i < mission_ack_2['count']; i++) {
          let point = {};
          let lat = resdt[begin] * 1;
          point['lat'] = lat;
          begin += 1;
          let lng = resdt[begin] * 1;
          point['lng'] = lng;
          begin += 1;
          point['alt'] = (resdt[begin] * 1).toFixed(2);
          begin += 1;
          point['v'] = (resdt[begin] * 1).toFixed(2);
          begin += 1;
          mission_ack_2['points'][i] = point;
        }
        _this.setState({
          infos: {
            ..._this.state.infos,
            mission_ack_2: mission_ack_2,
          },
          /*****收到飞机返回的航路数据，在地图上画航路和初始化右侧points列表*****/
          polylineArr: mission_ack_2['points'].map(data=> {
            let curPosition = {
              lat: wgs84togcj02(data.lng, data.lat)[1],
              lng: wgs84togcj02(data.lng, data.lat)[0],
            };
            return {lat: curPosition.lat, lng: curPosition.lng}
          }),
          center: {lat: mission_ack_2['points'][0].lat, lng: mission_ack_2['points'][0].lng},
          markers: mission_ack_2['points'].map((marker, index)=> {
            let curPosition = {
              lat: wgs84togcj02(marker.lng, marker.lat)[1],
              lng: wgs84togcj02(marker.lng, marker.lat)[0],
            };
            return {
              position: curPosition,
              defaultAnimation: 2,
              draggable: false,
              key: index,
              icon: {
                url: MARKERBLUE,
                scaledSize: new google.maps.Size(18, 32),
                size: new google.maps.Size(18, 32),
                origin: new google.maps.Point(0, 0),//The position of the image within a sprite, if any. By default, the origin is located at the top left corner of the image (0, 0)
                anchor: new google.maps.Point(9, 29),//The position at which to anchor an image in correspondence to the location of the marker on the map. By default, the anchor is located along the center point of the bottom of the image(25,50).
                labelOrigin: new google.maps.Point(9, 11)
              },
              label: {
                text: index.toString(),
                color: '#fff'
              },
              title: index.toString(),
              showInfo: false,
              isHover: false,
              zIndex: 0,
              content: `欢迎来到${index.toString()}号空间站`,

              alt: marker.alt,
              v: marker.v,
            }
          }),
          pointLists: mission_ack_2['points'].map((point, index)=> {
            return {
              'title': '航点',
              'id': index,
              'label1': '经度',
              'label2': '纬度',
              'label3': '速度',
              'label4': '高度',
              'lon': point.lng,
              'lat': point.lat,
              'v': point.v,
              'alt': point.alt,
            }
          })
        });
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 109) {
      /*****航路数据应答mission_ack3*****/
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        let mission_ack_3 = {};
        mission_ack_3['target_uav'] = resdt[begin];
        begin += 1;
        mission_ack_3['target_system'] = resdt[begin];
        begin += 1;
        mission_ack_3['type'] = resdt[begin];
        begin += 1;
        mission_ack_3['count_em'] = resdt[begin];
        begin += 1;
        mission_ack_3['point'] = [];
        for (var i = 0; i < mission_ack_3['count_em']; i++) {
          let point = {};
          let lat = resdt[begin];
          point['lat'] = (lat / Math.PI) * 180 - 0.002450;
          begin += 1;
          let lon = resdt[begin];
          point['lon'] = (lon / Math.PI) * 180 + 0.004740;
          begin += 1;
          point['alt'] = (resdt[begin] * 1).toFixed(2);
          begin += 1;
          mission_ack_3['point'][i] = point;
        }
        _this.setState({
          infos: {
            ..._this.state.infos,
            mission_ack_3: mission_ack_3,
          }
        });
        // console.log('infos is ', _this.state.infos)
      }
    } else if (msgid == 125) {
      /*****图片分批回传*****/
        // console.log('msgid', msgid, 'id length', resdt.byteLength);
      let image_data = {};
      begin += 1;
      if (resdt.getUint32(begin, true) == _this.state.flightID) {
        begin += 4;
        image_data['time_std_s'] = resdt.getUint32(begin, true);
        begin += 4;
        image_data['image_id'] = resdt.getUint32(begin, true);
        var imageId = resdt.getUint8(begin);
        begin += 4;
        image_data['image_piece_num'] = resdt.getUint8(begin);
        begin += 1;
        image_data['image_piece_id'] = resdt.getUint8(begin);
        begin += 1;
        if (!imageReturn[imageId]) {
          imageReturn[imageId] = {};
          imageReturn[imageId]['image_data'] = {};
        }
        imageReturn[imageId]['image_data'] = image_data;
        if (imageReturn[imageId]['image_data']['image_id'] == image_data['image_id']) {
          var len = resdt.byteLength - begin;
          var pic = "";
          var arr = new Uint8Array(finalData, begin, len);
          for (var i = 0; i < arr.length; ++i) {
            pic += String.fromCharCode(arr[i]);
          }
          imageAllData += pic;
          if (imageReturn[imageId]['image_data']['image_piece_id'] + 1 == imageReturn[imageId]['image_data']['image_piece_num']) {
            imageAllData = btoa(imageAllData);
            if (_this.state.infos.heartbeat && _this.state.infos.heartbeat.base_mode && _this.state.infos.heartbeat.base_mode == 33) {
              if (_this.curImageInterval) {
                clearInterval(_this.curImageInterval);
                _this.setState({
                  imgUpdata: 0,
                });
              }
              _this.setState({
                remoteControlVisible: true,
                remoteImg: 'data:image/jpg;base64,' + imageAllData
              });
              _this.curImageInterval = setInterval(function () {
                _this.setState({
                  imgUpdata: ++_this.state.imgUpdata
                });
              }, 1000)
            } else {
              _this.setState({
                isairWayRebackImage: true,
                airWayRebackImage: ('data:image/jpg;base64,' + imageAllData),
              })
            }
            imageAllData = '';
          }
        }
      }
    } else if (msgid == 245) {
      // console.log('msgid', msgid, ' 数据是  ', resdt);
      begin += 1;
      let id = resdt[begin];
      begin += 1;
      let codeResult = resdt[begin];
      if (codeResult == 0) {
        message.success("应急停浆指令发送成功！");
      } else if (codeResult == 1) {
        message.warning("权限不足！")
      } else if (codeResult == 2) {
        message.error("验证码不对！")
      }
    } else if (msgid == 246) {
      begin += 1;
      // 是否是当前页面飞机的246
      if (resdt[begin] == _this.state.flightID || !_this.state.flightID) {
        console.log('msgid', msgid, ' 数据是  ', resdt);
        let id = resdt[begin];
        begin += 1;
        let flightTime = resdt[begin];
        begin += 1;

        /*****设置延时，防止没有收到心跳包*****/
        _this.flightTimer = setTimeout(function () {
          if (id == _this.state.flightID) {

            // 是否飞行中
            if (_this.state.infos['heartbeat']['base_mode'] >= 3 || _this.state.infos['heartbeat']['base_mode'] == 0) {
              _this.IntervalTimer = setInterval(function () {
                let date = new Date();
                let curtime = (date.getTime() / 1000).toFixed(0);
                let tempTime = curtime - flightTime;
                let curMin = parseInt(tempTime / 60);
                curMin = curMin < 10 ? ('0' + curMin) : curMin;
                let curSec = (tempTime % 60).toFixed(0);
                curSec = curSec < 10 ? ('0' + curSec) : curSec;
                let tHtml = curMin + ":" + curSec;
                // console.log('tHtml is ', tHtml, tempTime);
                _this.setState({
                  infos: {
                    ..._this.state.infos,
                    flight_time: tHtml
                  },
                });
                /***** console.log('超过一定30分钟，清除飞行时间');*****/
                if (tempTime > 1800) {
                  clearInterval(_this.IntervalTimer);
                  _this.setState({
                    infos: {
                      ..._this.state.infos,
                      flight_time: 0
                    },
                  })
                }
              }, 1000);
            } else {
              console.log('收到246判断状态，不是航路等状态，清除定时器，并将飞行时间设置为零！');
              clearInterval(_this.IntervalTimer);
              _this.setState({
                infos: {
                  ..._this.state.infos,
                  flight_time: 0
                },
              })
            }
          }
        }, 5000)
      }
    } else if (msgid == 247) {
      console.log('msgid', msgid);
      message.warning('抱歉，没有权限');
    } else if (msgid == 248) {
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        console.log('msgid', msgid, resdt);
        let id = resdt[begin];
        begin += 1;
        let result = resdt[begin];
        if (result == true || _this.state.flightID != id) {
          message.warning('控制获取失败');
        }
      }
    } else if (msgid == 253) {
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        console.log('msgid', msgid);
        let id = resdt[begin];
        begin += 2;
        if (_this.state.infos['heartbeat']['id_uav_xyi'] == id) {
          let len = resdt.length;
          let Temp = resdt.slice(begin, len);
          let s;
          let uid = "";
          for (s in Temp) {
            uid += String.fromCharCode(Temp[s]);
          }
          Modal.confirm({
            title: '授权页面',
            content: `有新用户请求授权，确定要授权吗？`,
            okText: '授权',
            cancelText: '一遍玩蛋去',
            onOk: ()=> {
              let WSData = [
                251,
                _this.state.flightID,
                uid.length
              ];
              for (var i = 0; i < uid.length; i++) {
                WSData.push(uid[i].charCodeAt())
              }
              console.log('发送的数据是 ', JSON.stringify(WSData));
              // _this.state.WebSocket.send(JSON.stringify(WSData));
            }
          });
        }
      }
    } else if (msgid == 250) {
      console.log('msgid', msgid, '  返回数据是  ', resdt);
      begin += 1;
      if (resdt[begin] == _this.state.flightID) {
        let id = resdt[begin];
        begin += 2;
        let len = resdt.length;
        let TempToken = resdt.slice(begin, len);
        let s;
        let token = '';
        for (s in TempToken) {
          token += String.fromCharCode(TempToken[s]);
        }
        _this.setState({
          infos: {
            ..._this.state.infos,
            token: token
          }
        });
        console.log('控制成功!');
      }
    } else if (msgid == 254) {
      // console.log('msgid', msgid);
      begin += 1;
      let id = resdt[begin];
      if (_this.state.infos['heartbeat']['id_uav_xyi'] == id) {
        begin += 1;
        let type = resdt[begin];
        console.log("254type is ", type);
        if (type == 0) {
          _this.setState({
            infos: {
              ..._this.state.infos,
              heartbeat: {
                ..._this.state.infos.heartbeat,
                base_mode: '0'
              }
            },
            wideSignalStatus: false,
            localSignalStatus: false,
          })
        }
        if (type == 2) {
          _this.setState({
            wideSignalStatus: false,
          });
          if (_this.wideSignalTimeout) {
            clearTimeout(_this.wideSignalTimeout);
          }
          _this.wideSignalTimeout = setTimeout(function () {
            _this.setState({
              wideSignalStatus: true,
            })
          }, 5000);
        }
        if (type == 3) {
          _this.setState({
            localSignalStatus: false,
          });
          if (_this.localSignalTimeout) {
            clearTimeout(_this.localSignalTimeout);
          }
          _this.localSignalTimeout = setTimeout(function () {
            _this.setState({
              localSignalStatus: true,
            })
          }, 5000);
        } else {
          if (_this.state.infos.time_step) {
            _this.setState({
              infos: {
                ..._this.state.infos,
                time_step: (new Date().getTime() / 1000).toFixed(0) - _this.state.infos.time_step.toFixed(0) - _this.state.infos.last_date,
              },
            })
          }
        }
      }
    }
    // else {
    //   console.warn('Msgid=' + msgid + ' is not found!', ' Msg Length is ' + resdt.length);
    // }
  }

  handleErroData(data) {
    console.log('websocket发生发生错误，请重试', data)
  }

  /*****飞机状态图标改变*****/
  changeIconStatus() {
    let params = (this.state.infos.heartbeat.system_status).toString(2);
    if (params.length <= 1) {
      params = '00000000';
    }
    let length = params.length;
    for (var i = length - 1; i >= 0; i--) {
      var type = control_icons.ids[length - 1 - i];
      // console.log('type is ', type, ' paramss is  ', params[i], ' src is  ', '../img/gene/ctrlogo/' + control_icons.status[params[i]] + control_icons.icons[type]);
      if (type == 'mmc') {
        this.setState({
          iconStatus: {
            ...this.state.iconStatus,
            mmc: [params[i]],
          }
        })
      }
      if (type == 'fc') {
        this.setState({
          iconStatus: {
            ...this.state.iconStatus,
            fc: [params[i]],
          }
        })
      }
      if (type == 'local') {
        this.setState({
          iconStatus: {
            ...this.state.iconStatus,
            local: [params[i]],
          }
        })
      }
      if (type == '3g') {
        this.setState({
          iconStatus: {
            ...this.state.iconStatus,
            '3g': [params[i]],
          }
        })
      }
      if (type == 'camera') {
        this.setState({
          iconStatus: {
            ...this.state.iconStatus,
            camera: [params[i]],
          }
        })
      }
      if (type == 'ultrasonic') {
        this.setState({
          iconStatus: {
            ...this.state.iconStatus,
            ultrasonic: [params[i]],
          }
        })
      }
      if (type == 'camerab1') {
        this.setState({
          iconStatus: {
            ...this.state.iconStatus,
            camerab1: [params[i]],
          }
        })
      }
      if (type == 'b2') {
        this.setState({
          iconStatus: {
            ...this.state.iconStatus,
            b2: [params[i]],
          }
        })
      }
    }
  }

  /*****
   * 点击飞机或捷雁塔定位图标定位到该图标
   * @param arg
   */
  locationIcon(arg) {
    let _this = this;
    let id = arg.id;
    let markers = this.state.markers;
    for (var i = 0; i < markers.length; i++) {
      console.log('当前行id is  ', id, '  markers id is ', markers[i].key)
      if (id == markers[i].key) {
        let curcenter = {
          lat: markers[i].position.lat,
          lng: markers[i].position.lng
        }
        _this.setState({
          center: curcenter
        });
      }
    }
  }

  /*****
   * 关闭或展开所有航路点
   * @param checked
   */
  onPointsSwitchChange = (checked)=> {
    let activekeyArr = [];
    let pointLists = this.state.pointLists;
    for (var i = 0; i < pointLists.length; i++) {
      activekeyArr.push((pointLists[i].id).toString())
    }
    if (checked) {
      this.setState({
        pointsActive: activekeyArr,
      })
    } else {
      this.setState({
        pointsActive: [],
      })
    }
    // console.log(`switch to ${checked}`,activekeyArr);
  }
  onChange = (e)=> {
    console.log(e)
  }

  /****
   *点击Collapse头部，展开航点信息，同时左侧地图相对应航点处触发点击事件，InfoWindow框出现
   * @param e
   */
  pointCollapseChnage(e) {
    let newKey = (e.length > this.state.pointsActive.length ? e.diff(this.state.pointsActive) : this.state.pointsActive.diff(e)).toString();
    console.log(newKey);
    this.setState({
      pointsActive: e,
      markers: this.state.markers.map((marker, index)=> {
        if (index == newKey) {
          return {
            ...marker,
            showInfo: !marker.showInfo,
            icon: !marker.showInfo ? {
              url: MARKERBLUE,
              scaledSize: new google.maps.Size(27, 48),
              size: new google.maps.Size(27, 48),
              labelOrigin: new google.maps.Point(14, 14)
            } : {
              url: MARKERBLUE,
              scaledSize: new google.maps.Size(18, 32),
              size: new google.maps.Size(18, 32),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(9, 29),
              labelOrigin: new google.maps.Point(9, 11)
            },
            label: !marker.showInfo ? {
              text: index.toString(),
              color: '#fff',
              fontSize: '16',
            } : {
              text: index.toString(),
              color: '#fff',
              fontSize: '12',
            },
          }
        }
        return marker
      })
    })
  }

  /*****
   * 右侧输入框动态插入、删除航点,左侧地图跟着一起联动
   * @param key
   * @param type
   */
  pointPlusMinus(key, type) {
    let _this = this;
    /*****大家排队上车，一个一个执行————设置定时器，防止上一个函数collapse change——pointCollapseChnage()
     * 和它一起执行，，，然后各种奇葩问题。。。又掉坑里了，，，*****/
    this.timer = setTimeout(function () {
      let index = parseInt(key);
      if (key == 0 && type == 'minus') {
        message.warning('第一个航点不可删除');
        return
      } else if ((key == _this.state.markers.length - 1) && type == 'plus') {
        message.warning('最后一个航点不可再插入，请在地图上点击！');
        return
      } else {
        let curMarkers = _this.state.markers;
        let plusmarker = {
          position: {
            lat: (curMarkers[index].position.lat + curMarkers[index + 1].position.lat) / 2,
            lng: (curMarkers[index].position.lng + curMarkers[index + 1].position.lng) / 2
          },
          defaultAnimation: 2,
          draggable: true,
          key: Date.now(),
          icon: {
            url: MARKERBLUE,
            scaledSize: new google.maps.Size(18, 32),
            size: new google.maps.Size(18, 32),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(9, 29),
            labelOrigin: new google.maps.Point(9, 11)
          },
          label: {
            text: (index + 1).toString(),
            color: '#fff',
            fontSize: '12',
          },
          title: (index + 1).toString(),
          showInfo: false,
          isHover: false,
          zIndex: 0,
          content: `欢迎来到${(index + 1).toString()}号空间站`,
          v: '2.0', alt: '25',
        };
        if (type == 'plus') {
          let newmarkers = curMarkers.splice(index + 1, 0, plusmarker);
        } else {
          let newmarkers = curMarkers.splice(index, 1);
        }
        _this.setState({
          markers: curMarkers.map((marker, index)=> {
            return {
              position: {lat: marker.position.lat, lng: marker.position.lng},
              defaultAnimation: 2,
              draggable: false,
              key: `${Date.now() * Math.random()}${Date.now()}`,
              icon: {
                url: MARKERBLUE,
                scaledSize: new google.maps.Size(18, 32),
                size: new google.maps.Size(18, 32),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(9, 29),
                labelOrigin: new google.maps.Point(9, 11)
              },
              label: {
                text: index.toString(),
                color: '#fff'
              },
              title: index.toString(),
              showInfo: false,
              isHover: false,
              zIndex: 0,
              content: `欢迎来到${index.toString()}号空间站`,
              alt: marker.alt,
              v: marker.v,
            }
          }),
          polylineArr: curMarkers.map(data=> {
            return {lat: data.position.lat, lng: data.position.lng}
          }),
          pointLists: curMarkers.map((marker, index)=> {
            return {
              'title': '航点',
              'id': index,
              'label1': '经度',
              'label2': '纬度',
              'label3': '速度',
              'label4': '高度',
              'lon': marker.position.lng,
              'lat': marker.position.lat,
              'v': '2.00',
              'alt': '25.00',
            }
          }),
        });
      }
    }, 100)
  }

  searchAirwayOk = (e) => {
    console.log(e);
    this.setState({
      searchAirwayVisible: false,
    });
  }
  searchAirwayCancel = (e) => {
    console.log(e);
    this.setState({
      searchAirwayVisible: false,
    });
  }


  handleOnMouseMove = (e, obj, type, clickable)=> {
    // console.log(e, obj, type);
    if (type == 'img') {
      let spanXText = e.offsetX / this.state.imageWidth - 0.5;
      let spanYText = e.offsetY / this.state.imageHeight - 0.5;

      this.setState({
        XSpanStyle: {
          ...this.state.XSpanStyle,
          left: e.offsetX + 10,
          top: e.offsetY
        },
        YSpanStyle: {
          ...this.state.YSpanStyle,
          left: e.offsetX + 10,
          top: e.offsetY + 20
        },
        spanXText: spanXText,
        spanYText: spanYText,
      });
      if (clickable == 'click') {
        this.setState({
          spanXTextInput: spanXText,
          spanYTextInput: spanYText,
        });
      }
    } else {
      let spanXText = ((e.offsetX + obj.offsetLeft) / this.state.imageWidth) - 0.5;
      let spanYText = ((e.offsetY + obj.offsetTop) / this.state.imageHeight) - 0.5;
      this.setState({
        XSpanStyle: {
          ...this.state.XSpanStyle,
          left: e.offsetX + obj.offsetLeft + 10,
          top: e.offsetY + obj.offsetTop
        },
        YSpanStyle: {
          ...this.state.YSpanStyle,
          left: e.offsetX + obj.offsetLeft + 10,
          top: e.offsetY + obj.offsetTop + 20
        },
        spanXText: spanXText,
        spanYText: spanYText,
      })
      if (clickable == 'click') {
        this.setState({
          spanXTextInput: spanXText,
          spanYTextInput: spanYText,
        });
      }
    }
  }

  /*****发送websocket数据给飞机*****/
  flightControl(arg) {
    let _this = this;
    let WS = _this.state.WebSocket;
    let id = _this.state.flightID;
    let points = _this.state.pointLists;
    let WSData = [];
    if (arg == 'addflightline') {
      /*****装订航路*****/
      WSData = [105, id, 0, 0, points.length, 1];
      points.map(point=> {
        let newArr = [point.lon, point.lat, point.v, point.alt,];
        /*****注意concat不会改变原来的数据，只会返回合并后行的数组，所以将合并后新的数组再赋值给原来的数组*****/
        WSData = WSData.concat(newArr);
      });
    } else if (arg == 'searchflightline') {
      /*****查询航路*****/
      WSData = [107, id, 0, 0, 2,]
    } else if (arg == 'getflight') {
      /*****飞机起飞*****/
      WSData = [101, id, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0]
    } else if (arg == 'flightstop') {
      /*****应急着陆*****/
      WSData = [101, id, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0]
    } else if (arg == 'shutdownplane') {
      /*****应急着陆*****/
      WSData = [101, id, 0, 0, 14, 0, localStorage.getItem('username'), 0, 0, 0, 0, 0, 0]
    } else if (arg == 'missionpause') {
      /*****任务暂停or恢复*****/
      if (!_this.state.missionPauseStatus) {
        WSData = [101, id, 0, 0, 12, 0, 1, 0, 0, 0, 0, 0, 0]//任务暂停
      } else {
        WSData = [101, id, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0]//任务恢复
      }
      _this.setState({
        missionPauseStatus: !_this.state.missionPauseStatus
      })
    } else if (arg == 'gobackland') {
      /*****返回起点*****/
      WSData = [101, id, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0]
    } else if (arg == 'flightslowdown') {
      /*****应急减速*****/
      WSData = [101, id, 0, 0, 15, 0, _this.state.flightSlowDownValue, 0, 0, 0, 0, 0, 0]
      _this.setState({
        flightSlowDown: false,
        flightSlowDownValue: ''
      })
    } else if (arg == 'remotecontrol') {
      /*****进入远程控制*****/
      WSData = [101, id, 0, 0, 4, 0, 1.0, -1, 0, 0, 0, 0, 0]
      _this.setState({
        remoteControlVisible: true,
      });
      _this.imgBindMouseEvent();
    } else if (arg == 'quitremotecontrol') {
      /*****退出远程控制*****/
      if (_this.horizonTimer) {
        clearInterval(_this.horizonTimer);
      }
      if (_this.verticalTimer) {
        clearInterval(_this.verticalTimer);
      }
      if (_this.curImageInterval) {
        clearInterval(_this.curImageInterval);
      }
      _this.setState({
        horizonIntervalNum: 0,
        verticalIntervalNum: 0,
        remoteControlVisible: false,
        imgUpdata: 0,
      });
      WSData = [101, id, 0, 0, 4, 0, -1.0, 1, 0, 0, 0, 0, 0]
    } else if (arg == 'horizon') {
      /*****远程控制——水平移动*****/
      if (_this.horizonTimer) {
        clearInterval(_this.horizonTimer);
        _this.setState({
          horizonIntervalNum: 0,
        });
      }
      _this.horizonTimer = setInterval(function () {
        _this.setState({
          horizonIntervalNum: ++_this.state.horizonIntervalNum
        });
      }, 1000);
      WSData = [101, id, 0, 0, 4, 0, 1.0, 1, _this.state.spanXTextInput, _this.state.spanYTextInput, -1, 0, 0]
    } else if (arg == 'vertical') {
      /*****远程控制——垂直移动*****/
      if (_this.verticalTimer) {
        clearInterval(_this.verticalTimer);
        _this.setState({
          verticalIntervalNum: 0,
        });
      }
      _this.verticalTimer = setInterval(function () {
        _this.setState({
          verticalIntervalNum: ++_this.state.verticalIntervalNum
        });
      }, 1000)
      WSData = [101, id, 0, 0, 4, 0, 1.0, -1, 0, 0, 1, _this.state.spanZTextInput, 0]
    } else if (arg == 'verticalgound') {
      /*****远程控制——垂直降落到地面*****/
      WSData = [101, id, 0, 0, 4, 0, 1.0, -1, 0, 0, 1, 100, 0]
    } else if (arg == 'pid') {
      /*****pid控制调参*****/
      WSData = [101, id, 0, 0, 3, _this.state.infos.heartbeat.system_status, _this.state.pidValue1, _this.state.pidValue2, _this.state.pidValue3, _this.state.pidValue4, _this.state.pidValue5, _this.state.pidValue6, _this.state.pidValue7,]
    } else if (arg == 'xppid') {
      /*****XPpid控制调参*****/
      WSData = [101, id, 0, 0, 10, _this.state.infos.heartbeat.system_status, _this.state.pidValue1, _this.state.pidValue2, _this.state.pidValue3, _this.state.pidValue4, _this.state.pidValue5, _this.state.pidValue6, _this.state.pidValue7,]
    } else if (arg == 'offset') {
      /*****设置当地坐标偏移*****/
      WSData = [101, id, 0, 0, 7, 0, _this.state.offSetLon, _this.state.offSetLat, 0, 0, 0, 0, 0]
    } else if (arg == 'localgpsoffset') {
      /*****设置当地坐标偏移*****/
      WSData = [101, id, 0, 0, 8, 0, _this.state.uavLocalGpsOffsetValue, 0, 0, 0, 0, 0, 0]
    }

    console.log('websocket 发送的数据是 ', WSData);
    // WS.send(JSON.stringify(WSData));
  }

  imgBindMouseEvent() {
    let _this = this;
    _this.timer = setTimeout(function () {
      if (_this.state.remoteControlVisible) {
        /*****React通过refs获取DOM，也可直接通过原生js(document.getElementById)获取dom*****/
        let ImgZoomDOM = _this.refs['imgZoom'];
        let CenterCircle = _this.refs['centerCircle'];
        let CenterRec = _this.refs['centerRec'];
        /*****获取DOM之后给DOM绑定鼠标事件*****/
        ImgZoomDOM.onmousemove = (e)=> _this.handleOnMouseMove(e, ImgZoomDOM, 'img', 'mouseover');
        ImgZoomDOM.onclick = (e)=> _this.handleOnMouseMove(e, ImgZoomDOM, 'img', 'click');
        CenterCircle.onmousemove = (e)=> _this.handleOnMouseMove(e, CenterCircle, 'circle', 'mouseover');
        CenterCircle.onclick = (e)=> _this.handleOnMouseMove(e, CenterCircle, 'circle', 'click');
        CenterRec.onmousemove = (e)=> _this.handleOnMouseMove(e, CenterRec, 'rectangle', 'mouseover');
        CenterRec.onclick = (e)=> _this.handleOnMouseMove(e, CenterCircle, 'rectangle', 'click');
      }
    }, 300)
  }

  saveAirwayNameBtn() {
    let _this = this;
    let data = [];
    _this.state.pointLists.map(point=> {
      let obj = {
        lat: point.lat,
        lon: point.lon,
        alt: point.alt,
        v: point.v,
      };
      data.push(obj)
    });
    let saveAirwayName = this.state.saveAirwayName;
    let reg = /[\u4E00-\u9FA5]/;
    if (saveAirwayName == '') {
      message.warning('什么都不输(输入为空)，不太好好吧？');
    } else if (!reg.test(saveAirwayName)) {
      let url = `http://g1.xyitech.com:9999/submitroute?name=${saveAirwayName}&detail=${JSON.stringify(data)}`;
      console.log('保存航点url', url);
      // fetch(url)
      //   .then(function (response) {
      //     return response.json()
      //   })
      //   .then(function (data) {
      //     if (data.err == 0) {
      //       message.success('保存航路成功！', 2);
      //        _this.setState({
      //          saveAirwayVisible: false,
      //         })
      //     } else {
      //       message.error('人品不行，保存失败！', 2);
      //     }
      //   })
      //   .catch(function (e) {
      //     console.log("Oops, error", e);
      //     message.error('你想要的地球没有，请到火星看看！', 2);
      //     _this.setState({
      //       loading: false,
      //     });
      //   });
    } else {
      message.warning('这个世界，中文属于火星文，请输入不含中文字符的航路名');
    }
  }

  /*****
   * 监控页面查找航路
   */
  searchAirway() {
    let _this = this;
    let airwayName = this.state.searchAirwayName;
    if (airwayName == '') {
      message.warning('什么都不输(输入为空)，不太好好吧？')
    } else {
      let url = `http://g1.xyitech.com:9999/route?name=${airwayName}`;
      console.log('查找航路url', url);
      fetch(url)
        .then(function (response) {
          return response.json()
        })
        .then(function (data) {
          console.log('data is ', data)
          if (data.err == 0) {
            if (data.items.length > 1) {
              _this.setState({
                airWaydatas: data.items,
                loading: false,
              });
            } else {
              message.error('人品不行，没有找到对应的航路，换个名称试试呗！！', 2);
              _this.setState({
                airWaydatas: [],
                loading: false,
              });
            }
          } else {
            message.error('人品不行，查找失败！', 2);
            _this.setState({
              airWaydatas: [],
              loading: false,
            });
          }
        })
        .catch(function (e) {
          console.log("Oops, error", e);
          message.error('你想要的地球没有，请到火星看看！', 2);
          _this.setState({
            airWaydatas: [],
            loading: false,
          });
        });
    }
  }

  clearRemoteAirWay() {
    let _this = this;
    let url = `http://g1.xyitech.com:9999/cleardata?fid=${this.state.flightID}`;
    // fetch(url)
    //   .then(function (response) {
    //     return response.json()
    //   })
    //   .then(function (data) {
    //     if (data.err == 0) {
    //       message.success('作死成功！', 2);
    //     } else {
    //       message.error('人品不行，作死失败！', 2);
    //     }
    //     _this.setState({
    //       loading: false,
    //     });
    //   })
    //   .catch(function (e) {
    //     console.log("Oops, error", e);
    //     message.error('你想要的地球没有，请到火星看看！', 2);
    //     _this.setState({
    //       loading: false,
    //     });
    //   });

  }

  onSelectChange(selectedRowKeys) {
    console.log('selectedRowKeys changed: ', selectedRowKeys)
    this.setState({selectedRowKeys});
  }

  uavsearchAirwayOk() {
    // console.log(this.state.rowSelectData);
    let rowAirwayData = JSON.parse(this.state.rowSelectData.detail);
    this.setState({
      polylineArr: rowAirwayData.map(data=> {
        let curPosition = {
          lat: wgs84togcj02(data.lon, data.lat)[1],
          lng: wgs84togcj02(data.lon, data.lat)[0],
        };
        return {lat: curPosition.lat, lng: curPosition.lng}
      }),
      center: {lat: rowAirwayData[0].lat, lng: rowAirwayData[0].lon},
      markers: rowAirwayData.map((marker, index)=> {
        let curPosition = {
          lat: wgs84togcj02(marker.lon, marker.lat)[1],
          lng: wgs84togcj02(marker.lon, marker.lat)[0],
        };
        return {
          position: curPosition,
          defaultAnimation: 2,
          draggable: false,
          key: index,
          icon: {
            url: MARKERBLUE,
            scaledSize: new google.maps.Size(18, 32),
            size: new google.maps.Size(18, 32),
            origin: new google.maps.Point(0, 0),//The position of the image within a sprite, if any. By default, the origin is located at the top left corner of the image (0, 0)
            anchor: new google.maps.Point(9, 29),//The position at which to anchor an image in correspondence to the location of the marker on the map. By default, the anchor is located along the center point of the bottom of the image(25,50).
            labelOrigin: new google.maps.Point(9, 11)
          },
          label: {
            text: index.toString(),
            color: '#fff'
          },
          title: index.toString(),
          showInfo: false,
          isHover: false,
          zIndex: 0,
          content: `欢迎来到${index.toString()}号空间站`,

          alt: marker.alt,
          v: marker.v,
        }
      }),
      pointLists: rowAirwayData.map((point, index)=> {
        return {
          'title': '航点',
          'id': index,
          'label1': '经度',
          'label2': '纬度',
          'label3': '速度',
          'label4': '高度',
          'lon': point.lon,
          'lat': point.lat,
          'v': point.v,
          'alt': point.alt,
        }
      }),
      searchAirwayVisible: false,
    });
  }

  render() {
    const SYSTEMSTATUSICON = {
      S_ICON_MMC: require('../images/ctrl/ok/mmc.png'),
      S_ICON_FC: require('../images/ctrl/ok/fc.png'),
      S_ICON_3G: require('../images/ctrl/ok/3g.png'),
      S_ICON_LOCAL: require('../images/ctrl/ok/local.png'),
      S_ICON_CAMERA: require('../images/ctrl/ok/camera.png'),
      S_ICON_ULTRASONIC: require('../images/ctrl/ok/ultrasonic.png'),
      S_ICON_CAMERAB: require('../images/ctrl/ok/camerab1.png'),

      S_ICON_MMC_ERROR: require('../images/ctrl/error/mmc.png'),
      S_ICON_FC_ERROR: require('../images/ctrl/error/fc.png'),
      S_ICON_3G_ERROR: require('../images/ctrl/error/3g.png'),
      S_ICON_LOCAL_ERROR: require('../images/ctrl/error/local.png'),
      S_ICON_CAMERA_ERROR: require('../images/ctrl/error/camera.png'),
      S_ICON_ULTRASONIC_ERROR: require('../images/ctrl/error/ultrasonic.png'),
      S_ICON_CAMERAB_ERROR: require('../images/ctrl/error/camerab1.png'),
    };
    const flightSystemStatusData = [
      {
        'id': 's_mmc',
        'type': 'mmc',
        'imgsrcok': SYSTEMSTATUSICON.S_ICON_MMC,
        'imgsrcerror': SYSTEMSTATUSICON.S_ICON_MMC_ERROR,
        'text': '记载计算机'
      },
      {
        'id': 's_fc',
        'type': 'fc',
        'imgsrcok': SYSTEMSTATUSICON.S_ICON_FC,
        'imgsrcerror': SYSTEMSTATUSICON.S_ICON_FC_ERROR,
        'text': '飞控'
      },
      {
        'id': 's_3g',
        'type': '3g',
        'imgsrcok': SYSTEMSTATUSICON.S_ICON_3G,
        'imgsrcerror': SYSTEMSTATUSICON.S_ICON_3G_ERROR,
        'text': '广域通信'
      },
      {
        'id': 's_local',
        'type': 'local',
        'imgsrcok': SYSTEMSTATUSICON.S_ICON_LOCAL,
        'imgsrcerror': SYSTEMSTATUSICON.S_ICON_LOCAL_ERROR,
        'text': '局域通信'
      },
      {
        'id': 's_camera',
        'type': 'camera',
        'imgsrcok': SYSTEMSTATUSICON.S_ICON_CAMERA,
        'imgsrcerror': SYSTEMSTATUSICON.S_ICON_CAMERA_ERROR,
        'text': '摄像头'
      },
      {
        'id': 's_ultrasonic',
        'type': 'ultrasonic',
        'imgsrcok': SYSTEMSTATUSICON.S_ICON_ULTRASONIC,
        'imgsrcerror': SYSTEMSTATUSICON.S_ICON_ULTRASONIC_ERROR,
        'text': '超声波'
      },
      {
        'id': 's_camearb1',
        'type': 'camearb1',
        'imgsrcok': SYSTEMSTATUSICON.S_ICON_CAMERAB,
        'imgsrcerror': SYSTEMSTATUSICON.S_ICON_CAMERAB_ERROR,
        'text': '摄像头备用'
      },
    ];
    const SYSTEMTOPSTATUSICON = {
      S_ICON_TOP_IMG001: require('../images/titleimg/s_title_img001.png'),
      S_ICON_TOP_IMG002: require('../images/titleimg/s_title_img002.png'),
      S_ICON_TOP_IMG003: require('../images/titleimg/s_title_img003.png'),
      S_ICON_TOP_IMG004: require('../images/titleimg/s_title_img004.png'),
      S_ICON_TOP_IMG005: require('../images/titleimg/s_title_img005.png'),
      S_ICON_TOP_IMG006: require('../images/titleimg/s_title_img006.png'),
      S_ICON_TOP_IMG007: require('../images/titleimg/s_title_img007.png'),
      S_ICON_TOP_IMG008: require('../images/titleimg/s_title_img008.png'),
      S_ICON_TOP_IMG009: require('../images/titleimg/s_title_img009.png'),
    };
    const flightTopArgsData = [
      {
        'id': 'heartbeat_id_uav_xyi',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG001,
        'imgalt': '飞行器ID',
        'imgtitle': '飞行器ID',
        'text': this.state.infos.isInfos ? this.state.infos.heartbeat.id_uav_xyi : '0',
        'unit': ''
      },
      {
        'id': 'heartbeat_base_mode',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG002,
        'imgalt': '飞机状态',
        'imgtitle': '飞机状态',
        'text': this.state.infos.isInfos ? system_status_flag[this.state.infos.heartbeat.base_mode] : '0',
        'unit': ''
      },
      {
        'id': 'battery_status_battery_remaining',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG003,
        'imgalt': '电量',
        'imgtitle': '电量',
        'text': this.state.infos.isInfos ? this.state.infos.battery_status.battery_remaining : '0',
        'unit': '%'
      },
      {
        'id': 'global_position_int_relative_alt',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG004,
        'imgalt': '高度',
        'imgtitle': '高度',
        'text': this.state.infos.isInfos ? this.state.infos.global_position_int.relative_alt : '0',
        'unit': 'm'
      },
      {
        'id': 'local_position_ned_dis_m',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG005,
        'imgalt': '距离',
        'imgtitle': '距离',
        'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.dis_m : '0',
        'unit': 'm'
      },
      {
        'id': 'gps_raw_vel_gps2',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG006,
        'imgalt': '地速',
        'imgtitle': '地速',
        'text': this.state.infos.isInfos ? this.state.infos.gps_raw.vel_gps2 : '0',
        'unit': 'm/s'
      },
      {
        'id': 'local_position_ned_vz02',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG007,
        'imgalt': '升降速度',
        'imgtitle': '升降速度',
        'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.vz02 : '0',
        'unit': 'm/s'
      },
      {
        'id': 'battery_status_flight_time',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG008,
        'imgalt': '飞行时间',
        'imgtitle': '飞行时间',
        'text': this.state.infos.isInfos ? this.state.infos.flight_time : '0',
        'unit': ''
      },
      {
        'id': 'gps_raw_eph',
        'imgsrc': SYSTEMTOPSTATUSICON.S_ICON_TOP_IMG009,
        'imgalt': 'EPH',
        'imgtitle': 'EPH',
        'text': this.state.infos.isInfos ? this.state.infos.gps_raw.eph : '0',
        'unit': ''
      },
    ];
    const flightBottomArgsData = [
      {
        'block': [
          {
            'id': 'local_position_ned_time_std_s',
            'label': '时间戳',
            'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.time_std_s : '0',
            'unit': 's'
          },
          {
            'id': 'local_position_ned_x',
            'label': '北向坐标',
            'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.x : '0',
            'unit': 'm'
          },
          {
            'id': 'local_position_ned_y',
            'label': '东向坐标',
            'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.y : '0',
            'unit': 'm'
          },
          {
            'id': 'local_position_ned_z',
            'label': '天向坐标',
            'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.z : '0',
            'unit': 'm'
          },
        ]
      },
      {
        'block': [
          {
            'id': 'local_position_ned_vx',
            'label': '北向速度',
            'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.vx : '0',
            'unit': 'm/s'
          },
          {
            'id': 'local_position_ned_vy',
            'label': '东向速度',
            'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.vy : '0',
            'unit': 'm/s'
          },
          {
            'id': 'local_position_ned_vz',
            'label': '天向速度',
            'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.vz : '0',
            'unit': 'm/s'
          },
          {
            'id': 'global_position_int_hdg',
            'label': '航向',
            'text': this.state.infos.isInfos ? this.state.infos.global_position_int.hdg : '0',
            'unit': 'deg'
          },
        ]
      },
      {
        'block': [
          {
            'id': 'gps_raw_vel_gps',
            'label': 'GPS地速',
            'text': this.state.infos.isInfos ? this.state.infos.gps_raw.vel_gps : '0',
            'unit': 'm/s'
          },
          {
            'id': 'gps_raw_cog',
            'label': 'GPS地速方向',
            'text': this.state.infos.isInfos ? this.state.infos.gps_raw.cog : '0',
            'unit': 'deg'
          },
          {
            'id': 'global_position_int_pitch_deg',
            'label': '俯仰角',
            'text': this.state.infos.isInfos ? this.state.infos.global_position_int.pitch_deg : '0',
            'unit': ''
          },
          {
            'id': 'global_position_int_roll_deg',
            'label': '滚转角',
            'text': this.state.infos.isInfos ? this.state.infos.global_position_int.roll_deg : '0',
            'unit': ''
          },
        ]
      },
      {
        'block': [
          {
            'id': 'battery_status_time_can_fly',
            'label': '可飞时间',
            'text': this.state.infos.isInfos ? this.state.infos.battery_status.time_can_fly : '0',
            'unit': 's'
          },
          {
            'id': 'battery_status_time_needed',
            'label': '待飞时间',
            'text': this.state.infos.isInfos ? this.state.infos.battery_status.time_needed : '0',
            'unit': 's'
          },
          {
            'id': 'battery_status_voltages',
            'label': '电池电压',
            'text': this.state.infos.isInfos ? this.state.infos.battery_status.voltages : '0',
            'unit': ''
          },
          {
            'id': 'local_position_ned_ultra_alt',
            'label': '超声波高度',
            'text': this.state.infos.isInfos ? this.state.infos.local_position_ned.ultra_alt : '0',
            'unit': ''
          },
        ]
      },
      {
        'block': [
          {
            'id': 'vision_xyz_ned_vision_reg_num',
            'label': '图像识别数',
            'text': this.state.infos.isInfos ? this.state.infos.vision_xyz_ned.vision_reg_num : '0',
            'unit': ''
          },
          {
            'id': 'vision_xyz_ned_vision_x_ned',
            'label': 'X',
            'text': this.state.infos.isInfos ? this.state.infos.vision_xyz_ned.vision_x_ned : '0',
            'unit': ''
          },
          {
            'id': 'vision_xyz_ned_vision_y_ned',
            'label': 'Y',
            'text': this.state.infos.isInfos ? this.state.infos.vision_xyz_ned.vision_y_ned : '0',
            'unit': ''
          },
          {
            'id': 'vision_xyz_ned_vision_z_ned',
            'label': 'Z',
            'text': this.state.infos.isInfos ? this.state.infos.vision_xyz_ned.vision_z_ned : '0',
            'unit': ''
          },
        ]
      }
    ];
    const airWayColumns = [
      {
        title: '航路id',
        dataIndex: 'id',
        render: text => <a href="#">{text}</a>,
      },
      {
        title: '航路名称',
        dataIndex: 'name',
      }, {
        title: '航点数',
        render: (text, record) => {
          var airwayArray = JSON.parse(record.detail);
          return airwayArray.length;
        },
      }];

    const wideSignalCls = classNames('singnal-status', {'singnal-error': !this.state.wideSignalStatus});
    const localSignalCls = classNames('singnal-status', {'singnal-error': !this.state.localSignalStatus});
    return (
      <div className="map-container" id="mapContainer">
        <div className="mointer-container">
          <div className={this.state.rightIconStatus ? 'top-conainer' : 'top-conainer width-all'}>
            <Menu
              className="top-menu"
              onClick={this.handleClick}
              selectedKeys={[this.state.current]}
              mode="horizontal"
            >
              <SubMenu key="controls" title={<span><Icon type="tool"/>操控</span>}>
                <Menu.Item key="control:1">
                  <span onClick={()=>this.flightControl('addflightline') }>装订航线</span>
                </Menu.Item>
                <Menu.Item key="control:2">
                  <span onClick={()=>this.flightControl('searchflightline') }>查询航线</span>
                </Menu.Item>
                <Menu.Item key="control:3">
                  <span onClick={()=>this.flightControl('getflight') }>开始起飞</span>
                </Menu.Item>
                <Menu.Item key="control:4">
                  <span onClick={()=>this.flightControl('flightstop') }>应急着落</span>
                </Menu.Item>
                <Menu.Item key="control:6">
                 <span
                   onClick={()=>this.flightControl('missionpause') }>{!this.state.missionPauseStatus ? '任务暂停' : '任务恢复'}</span>
                </Menu.Item>
                <Menu.Item key="control:7">
                  <span onClick={()=>this.flightControl('gobackland') }>返回起点</span>
                </Menu.Item>
                <Menu.Item key="control:8">
                  <span onClick={()=>
                    Modal.confirm({
                      title: '应急停浆',
                      content: '确定要应急停浆吗？',
                      okText: '我要作死',
                      cancelText: '后悔了',
                      onOk: ()=> {
                        Modal.confirm({
                          title: '应急停浆',
                          content: '真的确定要应急停浆吗？',
                          okText: '继续作死',
                          cancelText: '后悔了',
                          onOk: ()=> {
                            Modal.confirm({
                              title: '应急停浆',
                              content: '真的真的确定要应急停浆吗？',
                              okText: '确定作死',
                              cancelText: '后悔了',
                              onOk: ()=> {
                                this.flightControl('shutdownplane')
                              }
                            })
                          }
                        })
                      }
                    })
                  }>应急停浆</span>
                </Menu.Item>
                <Menu.Item key="control:9">
                    <span onClick={()=> {
                      this.setState({
                        flightSlowDownModal: true
                      })
                    }}>应急减速</span>
                </Menu.Item>
              </SubMenu>
              <SubMenu key="flightdatas" title={<span><Icon type="database"/>数据</span>}>
                <Menu.Item key="flightdatas:1">
                  <span onClick={()=> {
                    this.setState({
                      saveAirwayVisible: true
                    })
                  }}>保存航路</span>
                </Menu.Item>
                <Menu.Item key="flightdatas:2">
                  <span onClick={()=> {
                    this.setState({
                      searchAirwayVisible: true
                    })
                  }}>查找航路</span>
                </Menu.Item>
                <Menu.Item key="flightdatas:3">
                  <span onClick={()=> {
                    Modal.confirm({
                      title: '清空本地航点',
                      content: '确定要清空本地航点吗？',
                      okText: '我要作死',
                      cancelText: '后悔了',
                      onOk: ()=> {
                        this.setState({markers: [], polylineArr: [], pointLists: [],})
                      }
                    })
                  }}>清空本地航路</span>
                </Menu.Item>
                <Menu.Item key="flightdatas:4">
                  <span onClick={()=> {
                    Modal.confirm({
                      title: '清空远程航路',
                      content: `确定要清空'${this.state.flightID}'远程航点吗？`,
                      okText: '我要作死',
                      cancelText: '后悔了',
                      onOk: this.clearRemoteAirWay()
                    })
                  }}>清空远程航路</span>
                </Menu.Item>
              </SubMenu>
              <SubMenu key="setting" title={<span><Icon type="setting"/>设置</span>}>
                <Menu.Item key="setting:1">申请控制</Menu.Item>
                <Menu.Item key="setting:7">
                   <span onClick={()=> {
                     this.setState({
                       uavPidVisible: true,
                       pid: 'pid',
                     })
                   }}>控制调参</span>
                </Menu.Item>
                <Menu.Item key="setting:2">
                 <span onClick={()=> {
                   this.setState({
                     uavOffSetVisible: true
                   })
                 }}>设置飞偏移</span>
                </Menu.Item>
                <Menu.Item key="setting:4">
                  <span onClick={()=> {
                    this.setState({
                      uavLocalGpsOffsetVisible: true
                    })
                  }}>设置相对高度差</span></Menu.Item>
                <Menu.Item key="setting:5">
                  <span onClick={()=> {
                    this.setState({
                      uavPidVisible: true,
                      pid: 'xppid',
                    })
                  }}>XP控制调参</span>
                </Menu.Item>
              </SubMenu>
            </Menu>
            <div className="top-status fr" key="light-status">
              <div className="curcontrol-status inbk">
                <p><span>当前权限：</span><span>{this.state.token ? '控制' : '查看'}</span></p>
              </div>
              <div className="communicate-cont inbk">
                <p className="singnal-status-gp"><span className={localSignalCls} id="signalWS">WS</span><span
                  className={wideSignalCls}
                  id="signal4G">4G</span>
                </p>
              </div>
            </div>
            <div className="single-top">
              {
                flightTopArgsData.map(ftad=> {
                  return (
                    <div className="single-top-block" key={ftad.id}>
                      <p><img className="s-title-img" src={ftad.imgsrc} alt={ftad.imgalt} title={ftad.title}/><span
                        className="f-status" id={ftad.id}>{ftad.text}</span>
                        <small>{ftad.unit}</small>
                      </p>
                    </div>
                  )
                })
              }
            </div>
          </div>
          <div className="s-left-icon">
            <div className={this.state.leftIconStatus ? 'f-icon' : 'f-icon hide'}>
              <table>
                <tbody id="ctlIcons">
                {
                  flightSystemStatusData.map(fssd=> {
                    return (
                      <tr key={fssd.id}>
                        <td><img id={fssd.id}
                                 src={this.state.iconStatus[fssd.type] == 0 ? fssd.imgsrcok : fssd.imgsrcerror}/><span
                          className={this.state.iconStatus[fssd.type] == 0 ? `${fIconSpanCls}` : `${fIconSpanCls} error`}>{fssd.text}</span>
                        </td>
                      </tr>
                    )
                  })
                }
                </tbody>
              </table>
            </div>
            <div className={this.state.leftIconStatus ? 'hideShowBtn rotate90' : 'hideShowBtn rotate270'}
                 title="关闭/打开飞机设备状态" onClick={()=> {
              this.setState({leftIconStatus: !this.state.leftIconStatus})
            }}></div>
          </div>
          <div className={this.state.rightIconStatus ? 's-bottom-bt' : 's-bottom-bt width-all'}>
            <div className="control-icons">
              <div className="control-icon" title="实时跟随" id="followAllTheTime"
                   onClick={()=>(this.setState({isfollowAllTheTime: !this.state.isfollowAllTheTime}))}>
                <img
                  src={!this.state.isfollowAllTheTime ? CONTROLICONS.FOLLOWFLIGHT : CONTROLICONS.FOLLOWFLIGHTACTIVE}/>
              </div>
              <div className="control-icon handsctrl" title="远程操控" id="uavCtrlByHands" onClick={()=> {
                this.flightControl('remotecontrol')
              }}>
                <img src={CONTROLICONS.REMOTE}/>
              </div>
              <div className="control-icon" title="切换实景地图" id="satellite" onClick={()=> {
                this.setState({mapTypeId: this.state.mapTypeId == 'satellite' ? 'roadmap' : 'satellite'})
              }}>
                <img src={this.state.mapTypeId == 'satellite' ? CONTROLICONS.TUCENGACTIVE : CONTROLICONS.TUCENG}/>
              </div>

              <div className="control-icon" title="定位飞机" id="locationFlight" onClick={
                ()=> {
                  this.setState({
                    center: this.state.infos.gps_raw.lat_gps ? {
                      lat: this.state.infos.gps_raw.lat_gps,
                      lng: this.state.infos.gps_raw.lon_gps
                    } : this.state.center
                  })
                }}>
                <img src={CONTROLICONS.GPS}/>
              </div>
            </div>
            <div className={this.state.bottomIconStatus ? 'blocks' : 'blocks hide'}>
              {
                flightBottomArgsData.map((fbad, index)=> {
                  return (
                    <div className="block" key={`${fbad.id}${index}`}>
                      {
                        fbad.block.map((block, index)=> {
                          return (
                            <p key={`${block.id}${index}`}>
                              <span className="label">{block.label}</span> : <span id={block.id}>{block.text}</span>
                              <small>{block.unit}</small>
                            </p>
                          )
                        })
                      }
                    </div>
                  )
                })
              }
            </div>
            <div className={this.state.bottomIconStatus ? 'hideShowBtn' : 'hideShowBtn rotate180'}
                 title="关闭/打开飞机数据" onClick={()=> {
              this.setState({bottomIconStatus: !this.state.bottomIconStatus})
            }}></div>
          </div>
          <div className="reback-img">
            <div className="left-main">
              <img src={this.state.isairWayRebackImage ? this.state.airWayRebackImage : REBACKIMG}/>
            </div>
            <div className="close-img"><img src={CLOSEREBACKIMG} alt="点我"/></div>
          </div>
          <div className={this.state.rightIconStatus ? 's-right' : 's-right hidden'} id="SRight">
            <div className={this.state.rightIconStatus ? 'points-conainer' : 'points-conainer hide'}>
              <div className="points-ctrl">
                <p>{this.state.pointsAllChecked ? '展开所有航点' : '折叠所有航点'}</p>
                <Switch defaultChecked={false} checkedChildren={'开'} unCheckedChildren={'关'}
                        onChange={this.onPointsSwitchChange.bind(this)}/>
              </div>
              <Collapse onChange={this.pointCollapseChnage.bind(this)} activeKey={this.state.pointsActive}>
                {
                  this.state.pointLists.map(point=> {
                    return (
                      <Panel
                        header={<p className="point-title"><span className="point-title">{`航点${point.id}`}</span><span
                          className="operation-span"><Icon type="plus-circle-o"
                                                           onClick={()=>this.pointPlusMinus(point.id, 'plus')}/><Icon
                          type="minus-circle-o" onClick={()=>this.pointPlusMinus(point.id, 'minus')}/></span></p>}
                        key={`${point.id}`}>
                        <div className="s-point">
                          <span className="point-label">{`${point.label1}:`}</span>
                          <Input placeholder={point.lon} value={point.lon} onChange={this.onChange}/>
                        </div>
                        <div className="s-point">
                          <span className="point-label">{`${point.label2}:`}</span>
                          <Input placeholder={point.lat} value={point.lat} onChange={this.onChange}/>
                        </div>
                        <div className="s-point">
                          <span className="point-label">{`${point.label3}:`}</span>
                          <Input placeholder={point.v} value={point.v} onChange={this.onChange}/>
                        </div>
                        <div className="s-point">
                          <span className="point-label">{`${point.label4}:`}</span>
                          <Input placeholder={point.alt} value={point.alt} onChange={this.onChange}/>
                        </div>
                      </Panel>
                    )
                  })
                }
              </Collapse>
            </div>
            <div className={this.state.rightIconStatus ? 'hideShowBtn rotate270' : 'hideShowBtn rotate90'}
                 title="隐藏/显示右侧航点" onClick={()=> {
              this.setState({rightIconStatus: !this.state.rightIconStatus})
            }}></div>
          </div>
          <AsyncGettingStartedExampleGoogleMap
            googleMapURL="http://ditu.google.cn/maps/api/js?v=3.exp&language=zh-CN&libraries=geometry,drawing&key=AIzaSyDEK4XKx_F2_R76kuxE_igcWbZpu1n14BQ&sensor=false&libraries=visualization"
            loadingElement={
              <div style={{height: `100%`}}>
                <Spin
                  size="large"
                  style={{
                    display: `block`,
                    width: `80px`,
                    height: `80px`,
                    margin: `150px auto`,
                    animation: `fa-spin 3s infinite linear`,
                  }}
                />
              </div>
            }
            loading={this.state.loading}
            containerElement={
              <div style={{height: `100%`}}/>
            }
            mapElement={
              <div style={{height: `100%`}}>
              </div>
            }
            mapdefaultProps={this.state.mapdefaultProps}
            center={this.state.center}
            mapTypeId={this.state.mapTypeId}
            onMapLoad={this.handleMapLoad}
            onMapClick={this.handleMapClick}
            markers={this.state.markers}
            polylineArr={this.state.polylineArr}
            onMarkerRightClick={this.handleMarkerRightClick}
            onMarkerDrag={this.handleMarkerDrag}

            onMarkerClick={this.handleMarkerClick}
            onCloseClick={this.handleCloseClick}
            onMarkerMouseOver={this.onMarkerMouseOver}
            onMarkerMouseOut={this.onMarkerMouseOut}

            flightMarker={this.state.flightMarker}
          />
          {this.state.isMapLoaded ? <WebsocketComp url='ws://jieyan.xyitech.com/control/create'
                                                   onOpen={this.websocketOnPen.bind(this)}
                                                   onMessage={this.state.isWebsocket ? this.handleData.bind(this) : this.websocketOnPen.bind(this)}
                                                   onError={this.handleErroData.bind(this)}
                                                   binaryType='arraybuffer'
                                                   debug={true}/> : ''
          }
        </div>
        <Modal
          title="远程操控"
          footer={null}
          wrapClassName="airway-image-container"
          width={this.state.airWayImageStyle.width}
          style={this.state.airWayImageStyle}
          visible={this.state.remoteControlVisible}
          onCancel={()=> {
            this.flightControl('quitremotecontrol')
          }}
        >
          <div className="collection-form-container">
            <div className="modal-image-area">
              <img className="image-zoom" id="imgZoom" src={this.state.remoteImg} alt="航路回传图"
                   ref='imgZoom'/>
              <p className="image-return-time">图像更新<span className="number-span"
                                                         id="singelImageTime">{`${this.state.imgUpdata}`}</span>秒
              </p>
              <div className="center-rec"
                   id="centerRec"
                   style={this.state.centerRecStyle}
                   ref='centerRec'></div>
              <div className="center-circle"
                   id="centerCircle"
                   style={this.state.centerCircleStyle}
                   ref='centerCircle'></div>
              <span id="spanX" style={this.state.XSpanStyle}>{`${this.state.spanXText}`}</span>
              <span id="spanY" style={this.state.YSpanStyle}>{`${this.state.spanYText}`}</span>
            </div>
            <div className="input-areas">
              <div className="input-items">
                <div className="input-item">
                  <p><span className="input-label">(X)</span><span
                    className="input-num">{`开始移动`}<strong>{`${this.state.horizonIntervalNum}`}</strong>秒</span></p>
                  <Input placeholder='请输入X轴距离' value={this.state.spanXTextInput} onChange={this.onChange}/>
                </div>
                <div className="input-item">
                  <p><span className="input-label">(Y)</span></p>
                  <Input placeholder='请输入Y轴距离' value={this.state.spanYTextInput} onChange={this.onChange}/>
                </div>
                <Button onClick={()=> {
                  this.flightControl('horizon')
                }}>水平移动</Button>
              </div>
              <div className="input-items">
                <div className="input-item">
                  <p><span className="input-label">(Z)</span><span
                    className="input-num">{`开始移动`}<strong>{`${this.state.verticalIntervalNum}`}</strong>秒</span></p>
                  <Input placeholder='请输入高度/m' value={this.state.spanZTextInput}
                         onChange={(e)=>this.setState({spanZTextInput: e.target.value})}/>
                </div>
                <Button onClick={()=> {
                  this.flightControl('vertical')
                }}>下降</Button>
              </div>
              <div className="input-items">
                <Button type='danger' onClick={()=> {
                  this.flightControl('verticalgound')
                }}>降落到地面</Button>
              </div>
              <div className="input-items">
                <Button type='dashed' onClick={()=> {
                  this.flightControl('quitremotecontrol')
                }}>退出</Button>
              </div>
            </div>
          </div>
        </Modal>
        <Modal
          title="应急减速"
          footer={null}
          visible={this.state.flightSlowDownModal}
          onCancel={()=>this.setState({flightSlowDownModal: false})}
        >
          <div className="collection-form-container">
            <Row gutter={24}>
              <Col className="gutter-row" span={4}>
                <div className="gutter-box">
                  <p className="modal-label">减速幅度</p>
                </div>
              </Col>
              <Col className="gutter-row" span={16}>
                <div className="gutter-box">
                  <Input placeholder='请输入应急减速速度m/s' value={this.state.flightSlowDownValue}
                         onChange={(e)=>this.setState({flightSlowDownValue: e.target.value})}/>
                </div>
              </Col>
              <Col className="gutter-row" span={3}>
                <div className="gutter-box">
                  <Button type='primary' onClick={()=> {
                    this.flightControl('flightslowdown')
                  }}>确定</Button>
                </div>
              </Col>
            </Row>
          </div>
        </Modal>
        <Modal
          title="控制调参"
          visible={this.state.uavPidVisible}
          onOk={()=> {
            this.flightControl(this.state.pid)
          }}
          onCancel={()=>this.setState({
            uavPidVisible: false,
          })}
        >
          <div className="collection-form-container">
            <Row gutter={24}>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='参数1' value={this.state.pidValue1}
                         onChange={(e)=>this.setState({pidValue1: e.target.value})}/>
                </div>
              </Col>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='参数2' value={this.state.pidValue2}
                         onChange={(e)=>this.setState({pidValue2: e.target.value})}/>
                </div>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='参数3' value={this.state.pidValue3}
                         onChange={(e)=>this.setState({pidValue3: e.target.value})}/>
                </div>
              </Col>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='参数4' value={this.state.pidValue4}
                         onChange={(e)=>this.setState({pidValue4: e.target.value})}/>
                </div>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='参数5' value={this.state.pidValue5}
                         onChange={(e)=>this.setState({pidValue5: e.target.value})}/>
                </div>
              </Col>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='参数6' value={this.state.pidValue6}
                         onChange={(e)=>this.setState({pidValue6: e.target.value})}/>
                </div>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='参数7' value={this.state.pidValue7}
                         onChange={(e)=>this.setState({pidValue7: e.target.value})}/>
                </div>
              </Col>
            </Row>

          </div>
        </Modal>
        <Modal
          title="设置飞机当地坐标偏移"
          visible={this.state.uavOffSetVisible}
          onOk={()=>this.flightControl('offset')}
          onCancel={()=>this.setState({
            uavOffSetVisible: false,
          })}
        >
          <div className="collection-form-container">
            <Row gutter={24}>
              <Col className="gutter-row" span={4}>
                <div className="gutter-box">
                  <p className="modal-label">经度偏移</p>
                </div>
              </Col>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='请输入经度偏移' value={this.state.offSetLon}
                         onChange={(e)=>this.setState({offSetLon: e.target.value})}/>
                </div>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col className="gutter-row" span={4}>
                <div className="gutter-box">
                  <p className="modal-label">纬度偏移</p>
                </div>
              </Col>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='请输入纬度偏移' value={this.state.offSetLat}
                         onChange={(e)=>this.setState({offSetLat: e.target.value})}/>
                </div>
              </Col>
            </Row>
          </div>
        </Modal>
        <Modal
          title="设置着落场相对高度差"
          visible={this.state.uavLocalGpsOffsetVisible}
          onOk={()=>this.flightControl('localgpsoffset')}
          onCancel={()=>this.setState({
            uavLocalGpsOffsetVisible: false,
          })}
        >
          <div className="collection-form-container">
            <Row gutter={24}>
              <Col className="gutter-row" span={4}>
                <div className="gutter-box">
                  <p className="modal-label">相对高度差</p>
                </div>
              </Col>
              <Col className="gutter-row" span={12}>
                <div className="gutter-box">
                  <Input placeholder='请输入相对高度差' value={this.state.uavLocalGpsOffsetValue}
                         onChange={(e)=>this.setState({uavLocalGpsOffsetValue: e.target.value})}/>
                </div>
              </Col>
            </Row>
          </div>
        </Modal>
        <Modal
          title="保存航路"
          footer={null}
          visible={this.state.saveAirwayVisible}
          onCancel={()=>this.setState({
            saveAirwayVisible: false,
          })}
        >
          <div className="collection-form-container">
            <Row gutter={24}>
              <Col className="gutter-row" span={4}>
                <div className="gutter-box">
                  <p className="modal-label">保存航路</p>
                </div>
              </Col>
              <Col className="gutter-row" span={16}>
                <div className="gutter-box">
                  <Input placeholder='请输入航路名称' value={this.state.saveAirwayName}
                         onChange={(e)=>this.setState({saveAirwayName: e.target.value})}/>
                </div>
              </Col>
              <Col className="gutter-row" span={4}>
                <div className="gutter-box">
                  <Button type="primary" onClick={()=>this.saveAirwayNameBtn()}>确定</Button>
                </div>
              </Col>
            </Row>
          </div>
        </Modal>
        <Modal
          title="查找航路"
          visible={this.state.searchAirwayVisible}
          onOk={()=>this.uavsearchAirwayOk()}
          onCancel={()=>this.setState({
            searchAirwayVisible: false,
          })}
        >
          <div className="collection-form-container">
            <Row gutter={24}>
              <Col className="gutter-row" span={4}>
                <div className="gutter-box">
                  <p>航路名称</p>
                </div>
              </Col>
              <Col className="gutter-row" span={16}>
                <div className="gutter-box">
                  <Input placeholder='请输入航路名称' value={this.state.searchAirwayName}
                         onChange={(e)=>this.setState({searchAirwayName: e.target.value})}/>
                </div>
              </Col>
              <Col className="gutter-row" span={4}>
                <div className="gutter-box">
                  <Button type="primary" onClick={()=>this.searchAirway()}>确定</Button>
                </div>
              </Col>
            </Row>
            <Table
              columns={airWayColumns}
              bordered
              scroll={{y: 200}}
              pagination={false}
              loading={this.state.loading}
              rowSelection={{
                type: 'radio',
                selectedRowKeys: this.state.selectedRowKeys,
                onChange: this.onSelectChange.bind(this),
                onSelect: (record)=>this.setState({
                  rowSelectData: record
                })
              }}
              rowKey={record => record.id}
              dataSource={this.state.airWaydatas}
            />
          </div>
        </Modal>
      </div>
    );
  }
}

const getBasicData = state => {
  return {}
}
export default connect(
  getBasicData,
  {}
)(ReactGoogleMapsComp)
